require! <[
  crypto
  path
  z85
  ./render
  ./atom
]>
require! {
  \js-yaml : yaml
  \fs-extra : fs
}

TIMEZONE = new Date().getTimezoneOffset()*60

sha256 = (buf)~>
  crypto.createHash('sha256').update(buf).digest!


_TIME = {}

hash = (filepath, buf, dir)~>
  hashpath = path.join(
    dir
    \li/sha256
    filepath
  )
  nowhash = sha256(buf)
  if await fs.pathExists hashpath
    oldhash = await fs.readFile hashpath
    if Buffer.compare oldhash.slice(0,32), nowhash
      outbuf = true
  else
    outbuf = true

  if outbuf
    now = parseInt(new Date() / 1000)
    buf = Buffer.allocUnsafe(6)
    buf.writeUIntBE(now, 0, 6)
    await fs.outputFile(
      hashpath
      Buffer.concat [
        nowhash
        buf
      ]
    )
  else
    now = oldhash.readUIntBE(32,6)
  _TIME[filepath] = now
  # console.log filepath, now

_atom = (dir, file-li)!~>
  file-li.sort ([a, ap],[b,bp])~>
    if a<0
      a = _TIME[ap]
    if b<0
      b = _TIME[bp]
    a - b
  host = (await fs.readFile(
    path.join dir, \6du/host.txt
    \utf-8
  )).trim!
  config = yaml.safeLoad await fs.readFile(
    path.join dir, \6du/html.yaml
    \utf-8
  )
  li = []
  for [time, filepath, txt , meta , atxt] in file-li.slice(-10)
    pos = txt.lastIndexOf '\n---\n'
    if pos > 0
      txt = txt.slice(0, pos)
    for i in <[作者 日期]>
      t = meta[i]
      if t
        atxt += "\n#i : #{meta[i]}"

    pos = txt.indexOf("# ")

    title = txt.slice(
      pos,
      txt.indexOf("\n", pos+1)
    ).slice(2)

    html = render(txt+atxt, filepath.slice(2,-3), config.cdn.img)
    li.push [
      title
      html
      filepath.slice(2,-3)
      meta['日期']
    ]
  await fs.outputFile(
    path.join(
      dir, "atom.xml"
    )
    atom(
      host
      config.txt.title
      li
    )
  )

日期 = '日期'

FILE_LI = []

trim-end = (txt)~>
  li = []
  for i in txt.replace(/\r\n/g,"\n").replace(/\r/g,"\n").split("\n")
    i = i.trimEnd!
    if i or li.length
      li.push i
  while li.length
    if li[li.length-1]
      break
    else
      li.pop()
  li.join('\n')+"\n"

module.exports = {
  end : (dir)!~>

    _atom dir, FILE_LI

    FILE_LI.sort ([a],[b])~>
      if a < 0 and b > 0
        return -1
      if a > 0 and b < 0
        return 1
      b - a

    txt = {}
    var pre

    for [time, filepath, ptxt, meta] in FILE_LI
      name = filepath.slice(0,-3)

      if time > 0
        q = (new Date(time*1000)).toISOString!.split("-",1)[0]-0
      else
        q = 0

      qli = txt[q] = txt[q] or []
      title = meta['链接标题']
      if title
        ptxt = "# #title\n" + ptxt.slice(ptxt.indexOf("\n")+1)
      qli.push "#name"+"\n"+ptxt

      # buf = Buffer.allocUnsafe(6+32+len)
      # buf.writeIntBE time, 0, 6
      # hash.digest!.copy buf, 6
      # buf.write name, 38, len
      # li.push buf
    li = []
    for year, tli of txt
      t = tli.join "------\n"
      li.push "#year,#{z85.encode sha256(t)}"
      await fs.outputFile(
        path.join dir, "li/#year.md"
        t
      )
    li = li.join("\n")
    await fs.outputFile path.join(dir, 'li/index.csv'), li

  file : (buf, dir)~>
    filepath = buf.path
    hash-change = hash(filepath, buf, dir)
    buf = buf.toString(\utf-8)
    buf = trim-end buf
    pos = buf.indexOf("\n------\n")
    if pos + 1
      ptxt = buf.slice(0,pos)
      atxt = buf.slice(pos)
      spos = ptxt.lastIndexOf('\n---\n')

      if spos + 1
        spos = spos+5
        head = ptxt.slice(0, spos)
        meta = ptxt.slice(spos)
      else
        head = []
        for i in ptxt.split("\n")
          if i.trim().startsWith "#"
            head.push(i)
        head = head.join('\n')
        if head
          head += "\n"
        meta = ptxt

      meta = (yaml.safeLoad meta) or {}
      if (日期 of meta)
        date = meta[日期]
        delete meta[日期]
      else
        date = (await fs.stat(filepath)).ctime
        date = new Date(date - TIMEZONE*1000)

      if Number.isInteger(date)
        date-str = date
      else
        date-str = date.toISOString().replace('T',' ').split(".")[0]
        date = parseInt(date/1000+TIMEZONE)

      li = []
      for k,v of meta
        li.push "#k : #v"
      li.sort()
      if typeof(date-str) == \string
        meta['日期'] = date-str
      li.push "#{日期} : "+date-str

      ptxt = head+'\n'+(li.join '\n')+"\n"
      buf = Buffer.from(ptxt+atxt+"\n")

      h1 = false
      for i in ptxt.split("\n")
        if i.startsWith "#"
          h1 = true
          break
      if h1
        line = [
          date
          filepath
          ptxt
          meta
          atxt
        ]
        FILE_LI.push(line)
      return buf
    return buf
}

